package com.example.multiactivity

import android.media.Image
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import android.graphics.Bitmap


// 定义全局变量：元素获取
private lateinit var image: ImageView;
private lateinit var takePictureButton: Button;
// Activity Result Launcher，用于拍照并获取 Bitmap
private lateinit var takePictureLauncher: ActivityResultLauncher<Void?>

class FourthActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_fourth)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        image = findViewById<ImageView>(R.id.image);
        takePictureButton = findViewById<Button>(R.id.takePictureButton);

        // 注册拍照回调
        takePictureLauncher = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) { bitmap: Bitmap? ->
            if (bitmap != null) {
                image.setImageBitmap(bitmap)
            }
        }

        // 点击按钮触发拍照
        takePictureButton.setOnClickListener {
            takePictureLauncher.launch(null)
        }
    }
}